import { changeModal, getGameAsync } from "@/store/game/gameSlice";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { Form, Input, Modal, Select, Upload } from "antd";
import { useEffect, useState, type ReactElement } from "react";
import { PlusOutlined } from "@ant-design/icons";
import { createGame, getDetail, updateGame } from "@/store/game/gameAPI";

export default function Create(): ReactElement<typeof Modal, "div"> {
  const [modalLoading, setModalLoading] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const { modal, params } = useAppSelector((state) => state.game);
  const {
    config: { data: { data: { user_channel_list = [], minigame_class = [] } = {} } = {} } = {},
  } = useAppSelector((state) => state.app);
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();

  const handleClose = () => {
    dispatch(changeModal({ open: false }));
    form.resetFields();
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      const p = new FormData();
      p.append("channel", values.channel);
      p.append("game_name", values.game_name);
      p.append("url", values.url);
      
      p.append("recommend", values.recommend);
      p.append("sort_value", values.sort_value);
      p.append("class_id", values.class_id);
      if(values?.image?.[0]?.originFileObj){
        p.append("image", values.image[0].originFileObj);
      }
      if(values?.icon?.[0]?.originFileObj){
        p.append("icon", values.icon[0].originFileObj);
      }
      if (modal.type === "create") {
        createGame(p)
          .then(() => {
            handleClose();
            dispatch(getGameAsync({ ...params }));
          })
          .finally(() => setLoading(false));
      } else if (modal.type === "update") {
        p.append("game_id", String(modal.record?.id));
        updateGame(p)
          .then(() => {
            handleClose();
            dispatch(getGameAsync({ ...params }));
          })
          .finally(() => setLoading(false));
      }
    } catch (err) {
      console.log("校验不通过");
    }
  };

  useEffect(() => {
    if (modal.open && modal.type === "update") {
      setModalLoading(true);
      getDetail({
        game_id: modal.record?.id as number,
      })
        .then((res) => {
          form.setFieldsValue(res.data);
          form.setFieldValue("icon", [
            {
              uid: "-1",
              name: res.data.icon,
              status: "done",
              url: res.data.icon,
            },
          ]);
          form.setFieldValue("image", [
            {
              uid: "-1",
              name: res.data.image,
              status: "done",
              url: res.data.image,
            },
          ]);
        })
        .finally(() => {
          setModalLoading(false);
        });
    }
  }, [modal]);

  return (
    <Modal
      open={modal.open}
      title={modal.type === "create" ? "创建" : "编辑"}
      onCancel={handleClose}
      onOk={handleOk}
      confirmLoading={loading}
      loading={modalLoading}
    >
      <Form form={form}>
        <Form.Item
          name="channel"
          rules={[{ required: true, message: "必填" }]}
          label="渠道"
        >
          <Select options={user_channel_list} />
        </Form.Item>
        <Form.Item
          name="game_name"
          rules={[{ required: true, message: "必填" }]}
          label="游戏名字"
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="url"
          rules={[{ required: true, message: "必填" }]}
          label="游戏链接"
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="图标"
          name="icon"
          rules={[{ required: true, message: "必填" }]}
          valuePropName="fileList"
          getValueFromEvent={(e) => (Array.isArray(e) ? e : e?.fileList)}
        >
          <Upload.Dragger beforeUpload={() => false} maxCount={1}>
            <button style={{ border: 0, background: "none" }} type="button">
              <PlusOutlined />
              <div style={{ marginTop: 8 }}>拖拽 或 选择</div>
            </button>
          </Upload.Dragger>
        </Form.Item>
        <Form.Item
          label="图片"
          name="image"
          rules={[{ required: true, message: "必填" }]}
          valuePropName="fileList"
          getValueFromEvent={(e) => (Array.isArray(e) ? e : e?.fileList)}
        >
          <Upload.Dragger beforeUpload={() => false} maxCount={1}>
            <button style={{ border: 0, background: "none" }} type="button">
              <PlusOutlined />
              <div style={{ marginTop: 8 }}>拖拽 或 选择</div>
            </button>
          </Upload.Dragger>
        </Form.Item>
        <Form.Item
          name="recommend"
          rules={[{ required: true, message: "必填" }]}
          label="是否推荐"
        >
          <Select
            options={[
              { label: "是", value: 1 },
              { label: "否", value: 2 },
            ]}
          />
        </Form.Item>
        <Form.Item
          name="sort_value"
          rules={[{ required: true, message: "必填" }]}
          label="排序值"
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="class_id"
          rules={[{ required: true, message: "必填" }]}
          label="分类id"
        >
          <Select options={minigame_class} />
        </Form.Item>
      </Form>
    </Modal>
  );
}
